#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : micah
# @time    :  
# @function: 
# @version :


import pymysql

# # 打开数据库链接
# db = pymysql.connect(host='localhost', port=3306, user='root', password='123456',)
# # 创建游标
# cursor = db.cursor()
# cursor.execute('select version()')
# print(cursor.fetchone())
# cursor.execute('CREATE DATABASE spiders10 DEFAULT CHARACTER SET utf8')
# db.close()

#
# def create_table():
#     db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db="spiders10")
#     # 使用cursor方法创建一个游标对象cursor
#     cursor = db.cursor()
#     # 使用预处理语句创建表
#     sql = '''
#     CREATE TABLE IF NOT EXISTS students (
#         id VARCHAR(255) NOT NULL,
#         name VARCHAR(255) NOT NULL,
#         age INT NOT NULL,
#         PRIMARY KEY (id))
#     '''
#     try:
#         cursor.execute(sql)
#         print("CREATE TABLE SUCCESS.")
#     except Exception as e:
#         print(f"CREATE TABLE FAILED,CASE{e}")
#     finally:
#         # 关闭数据库连接
#         db.close()
#
#
# def main():
#     create_table()
#
#
# if __name__ == '__main__':
#     main()



id = '00002'
user = 'micah'
age = 18


def insert_record():
    db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='spiders10')
    # 获取游标
    cursor = db.cursor()
    # SQL 插入语句
    sql = 'INSERT INTO students(id, name, age) values(%s, %s, %s)'
    # 执行SQL语句
    try:
        cursor.execute(sql, (id, user, age))
        # 提交到数据库执行
        db.commit()
        print('数据插入成功')
    except Exception as e:
        print(f'数据插入失败：{e}')
        # 如果发生错误就回滚
        db.rollback()
    finally:
        # 关闭数据库连接
        db.close()


if __name__ == '__main__':
    insert_record()
